package org.example.java.nio.channels;

import com.google.common.io.Files;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.util.concurrent.TimeUnit;

/**
 * 启动两个JVM 测试
 * Created by Juntao.Zhang on 2014/10/8.
 */
public class FileLocking {
  public static final String FILE_LOCK = "in_use.lock";

  public static void main(String[] args) throws Exception {
    File dir = Files.createTempDir();
    File file = new File(dir, FILE_LOCK);
    dir.deleteOnExit();
    file.deleteOnExit();
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    FileLock fl = raf.getChannel().tryLock();
    file.deleteOnExit();
    if (fl != null) {
      System.out.println("locked file");
      raf.write("hello world".getBytes());
      TimeUnit.SECONDS.sleep(5);
      fl.release();
      System.out.println("release file");
    }
    raf.close();
  }
}
